import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/file_item.dart';
import '../../services/minio_service.dart';
import '../../widgets/file_preview.dart';

class FileDetailScreen extends StatefulWidget {
  final FileItem file;

  const FileDetailScreen({Key? key, required this.file}) : super(key: key);

  @override
  State<FileDetailScreen> createState() => _FileDetailScreenState();
}

class _FileDetailScreenState extends State<FileDetailScreen> {
  bool _isLoading = false;
  String? _downloadUrl;

  @override
  void initState() {
    super.initState();
    _generateDownloadUrl();
  }

  Future<void> _generateDownloadUrl() async {
    if (widget.file.minioObjectName.isEmpty) return;
    
    setState(() => _isLoading = true);
    
    try {
      final minioService = Provider.of<MinioService>(context, listen: false);
      final url = await minioService.getFileUrl(widget.file.minioObjectName);
      setState(() {
        _downloadUrl = url;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取文件预览失败: $e')),
      );
    }
  }

  Future<void> _downloadFile() async {
    if (_downloadUrl == null) return;
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('下载功能需要在实际设备上实现')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.file.name),
        actions: [
          IconButton(
            icon: const Icon(Icons.download),
            onPressed: _downloadFile,
          ),
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('分享功能即将推出')),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // File info card
          Card(
            margin: const EdgeInsets.all(16),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      _getFileIcon(),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              widget.file.name,
                              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              widget.file.sizeFormatted,
                              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  const Divider(),
                  const SizedBox(height: 16),
                  _buildInfoRow('文件类型', widget.file.mimeType),
                  const SizedBox(height: 8),
                  _buildInfoRow('上传时间', _formatDateTime(widget.file.uploadedAt)),
                  const SizedBox(height: 8),
                  _buildInfoRow('文件路径', widget.file.path),
                ],
              ),
            ),
          ),
          
          // File preview
          Expanded(
            child: Card(
              margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
              child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _downloadUrl != null
                    ? FilePreview(
                        file: widget.file,
                        downloadUrl: _downloadUrl!,
                      )
                    : const Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.error_outline,
                              size: 48,
                              color: Colors.grey,
                            ),
                            SizedBox(height: 16),
                            Text(
                              '无法加载文件预览',
                              style: TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _getFileIcon() {
    IconData iconData;
    Color iconColor;

    if (widget.file.isImage) {
      iconData = Icons.image;
      iconColor = Colors.blue;
    } else if (widget.file.isVideo) {
      iconData = Icons.video_file;
      iconColor = Colors.red;
    } else if (widget.file.isAudio) {
      iconData = Icons.audio_file;
      iconColor = Colors.orange;
    } else if (widget.file.isDocument) {
      iconData = Icons.description;
      iconColor = Colors.green;
    } else {
      iconData = Icons.insert_drive_file;
      iconColor = Colors.grey;
    }

    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        color: iconColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Icon(
        iconData,
        color: iconColor,
        size: 24,
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 80,
          child: Text(
            label,
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: Theme.of(context).textTheme.bodySmall,
          ),
        ),
      ],
    );
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
           '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}